<template>
  <transition name="fade" @after-leave="afterLeave">
    <div class="modal" v-show="shown" :style="{zIndex: index}" @click="clickBgToClose">
      <transition name="v-slide">
        <div ref="panel" class="modal-dialog" v-show="shown" :style="panelStyle">
          <div class="modal-title">
            {{title}}
            <button v-if="showClose" type="button" class="btn btn-xs btn-link" @click="close"><i class="va-icon-times"></i></button>
          </div>
          <div class="modal-body" :style="{'max-height': maxContentHeight || null}">
            <slot></slot>
          </div>
        </div>
      </transition>
    </div>
  </transition>
</template>

<script>
  import _ from 'lodash'

  let initIndex = 2000
  let modalStack = []

  function closeModalByEsc (evt) {
    let keyCode = evt.keyCode ? evt.keyCode : evt.which
    if (keyCode === 27 && modalStack.length > 0) {
      let vm = modalStack[modalStack.length - 1]
      vm.close()
    }
  }

  function updateBodyStyle () {
    let body = _.head(document.getElementsByTagName('body'))
    if (body) {
      if (modalStack.length > 0) {
        body.style.setProperty('overflow', 'hidden', 'important')
      } else {
        body.style.setProperty('overflow', 'inherit')
      }
    }
  }

  export default {
    props: {
      title: {
        type: String
      },
      disableEscClose: {
        type: Boolean,
        default: false
      },
      staticModal: {
        type: Boolean,
        default: true
      },
      showClose: {
        type: Boolean,
        default: true
      },
      width: {},
      maxContentHeight: {
        type: String,
        default: null
      }
    },
    data () {
      return {
        index: initIndex,
        shown: false
      }
    },
    methods: {
      open () {
        initIndex++
        this.index = initIndex
        this.shown = true
        if (!this.disableEscClose) {
          modalStack.push(this)
          window.removeEventListener('keyup', closeModalByEsc)
          window.addEventListener('keyup', closeModalByEsc)
        }
        this.$emit('open')
      },
      close () {
        this.shown = false
        if (!this.disableEscClose) {
          modalStack.splice(_.indexOf(modalStack, this), 1)
          if (modalStack.length === 0) {
            window.removeEventListener('keyup', closeModalByEsc)
          }
        }
        this.$emit('close')
      },
      clickBgToClose (e) {
        if (!this.staticModal && !this.$refs.panel.contains(e.target)) {
          this.close()
        }
      },
      afterLeave () {
        this.$emit('closed')
      }
    },
    computed: {
      panelStyle () {
        return this.width ? `width: ${this.width}` : null
      }
    },
    watch: {
      shown () {
        updateBodyStyle()
      }
    },
    beforeDestroy () {
      this.close()
    }
  }
</script>
